package com.hdoit.apollo.web.billing.controllers;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hdoit.apollo.logical.billing.mapper.BillingMapper;
import com.hdoit.apollo.logical.billing.model.Billing;
import com.hdoit.apollo.logical.billing.model.BillingPrint;
import com.hdoit.apollo.logical.billing.service.IBillingPrintService;
import com.hdoit.apollo.logical.billing.service.IBillingRecordService;
import com.hdoit.apollo.logical.billing.service.IBillingService;
import com.hdoit.apollo.logical.common.enums.billing.BillingConfirm;
import com.hdoit.apollo.logical.common.enums.billing.BillingRecordType;
import com.hdoit.apollo.logical.common.enums.billing.BillingState;
import com.hdoit.apollo.logical.common.enums.billing.PayState;
import com.hdoit.apollo.logical.common.enums.billing.PrintType;
import com.hdoit.apollo.logical.common.enums.shop.CustomerRecordType;
import com.hdoit.apollo.logical.common.enums.shop.PayObject;
import com.hdoit.apollo.logical.shop.model.Payment;
import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.model.Staff;
import com.hdoit.apollo.logical.shop.service.ICustomerRecordService;
import com.hdoit.apollo.logical.shop.service.IPaymentService;
import com.hdoit.apollo.logical.shop.service.IStaffService;
import com.hdoit.apollo.logical.stock.model.OutStockCollocation;
import com.hdoit.apollo.logical.stock.model.OutStockShow;
import com.hdoit.apollo.logical.stock.model.Stock;
import com.hdoit.apollo.logical.stock.model.StockCollocation;
import com.hdoit.apollo.logical.stock.service.IOutStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IOutStockService;
import com.hdoit.apollo.logical.stock.service.IStockCollocationService;
import com.hdoit.apollo.logical.stock.service.IStockService;
import com.hdoit.apollo.logical.viewmodel.billing.BillingSearch;
import com.hdoit.apollo.logical.viewmodel.billing.BillingStat;
import com.hdoit.apollo.logical.viewmodel.billing.PrintDescribe;
import com.hdoit.apollo.logical.viewmodel.billing.BillingDetailed;
import com.hdoit.apollo.logical.viewmodel.stock.OutStockCollocationInfo;
import com.hdoit.apollo.logical.viewmodel.stock.ReturnCargoInfo;
import com.hdoit.apollo.logical.viewmodel.stock.SendOutGoodsInfo;
import com.tennetcn.authority.component.web.ActionResult;
import com.tennetcn.authority.component.web.BaseController;
import com.tennetcn.authority.component.web.ErrorResult;
import com.tennetcn.authority.component.web.JsonActionResult;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;
import com.tennetcn.web.message.WebManageContainer;

/**
 * @author      tancongzhu
 * @email       
 * @createtime  2018年04月26日 11:04:02
 * @comment
 */
@Controller
@RequestMapping(value = "/billing/billing/")
public class BillingController extends BaseController{
    @Override
    public String getRoutePath() {
        return "areas/billing/billing/";
    }

    @Autowired
    private IBillingService billingService;
    
    @Autowired
    private BillingMapper billingMapper;
    
	@Autowired
	private IStockService stockService;
	
	@Autowired
	private IStaffService staffService;
	
	@Autowired
	private IBillingRecordService billingRecordService;
	
	@Autowired
	private ICustomerRecordService customerRecordService;
	
	@Autowired
	private IOutStockService outStockService;
	
    @Autowired
    private IPaymentService paymentService;
    
    @Autowired
    private IStockCollocationService stockCollocationService;
    
    @Autowired
    private IOutStockCollocationService outStockCollocationService;
    
    @Autowired
    private IBillingPrintService billingPrintService;
    
    
    private final String indexViewName="index";
    private final String detailedIndexViewName="detailed/index";
    private final String summaryIndexViewName="summary/index";
    private final String outputViewName="output";
    private final String detailedOutputViewName="detailed/output";
    private final String summaryOutputViewName="summary/output";
    private final String addDetailed="addDetailed";//开单(添加)
    private final String detailedViewName="detailed";//开单(编辑查看)
    private final String saveViewName="save";
    private final String deleteViewName = "delete";
    private final String checkBillingState = "checkBillingState";//关闭订单
    private final String closeBillingByKey = "closeBillingByKey";
    private final String checkDetailed = "checkDetailed";//审核
    private final String checkSave="checkSave";
    private final String sendOutGoodsDetailed = "sendOutGoodsDetailed";//发货
    private final String sendOutGoodsSave="sendOutGoodsSave";
    private final String addPayDetailed = "addPayDetailed";//付款
    private final String addPaySave="addPaySave";
    private final String detailedPrint="print/detailedPrint";//先锋电子
    private final String billingPrint="print/billingPrint";
    
    private final String electricalPreview="print/electricalPreview";//致悦
    private final String electricalPrint="print/electricalPrint";
    private final String exportDetailed="exportDetailed";
    private final String returnCheck="returnCheck";
    private final String returnCheckSave="returnCheckSave";
    
    @RequestMapping(value = indexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String index(Model model,PagerModel pagerModel,BillingSearch search,boolean ajaxPost){
    	search.setType("notShipped");
    	//BillingStatForPC billingStat=billingMapper.queryStat(search);
    	

        pagerModel.setTotalAmount(billingMapper.queryCountMPForPc(search));
        List<Billing> billings= billingMapper.queryListMPForPc(search,pagerModel);

        model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("billings", billings);
        model.addAttribute("billingSearch", search);
        //model.addAttribute("billingStat", billingStat);

        if(ajaxPost){
            return view(outputViewName);
        }

        return view(indexViewName);
    }
    
    @RequestMapping(value = detailedIndexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String detailedIndex(Model model,PagerModel pagerModel,BillingSearch search,boolean ajaxPost){
    	search.setType("notShipped");
    	search.setBillingState(BillingState.completed);
    	pagerModel.setTotalAmount(outStockCollocationService.queryCountByDetailed(search));
    	List<BillingDetailed> billingDetaileds=outStockCollocationService.queryListByDetailed(search,pagerModel);
    	BillingStat billingStat=outStockCollocationService.querySummaryStat(search);
    	
    	model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("billingDetaileds", billingDetaileds);
        model.addAttribute("billingStat", billingStat);
        model.addAttribute("billingSearch", search);

        if(ajaxPost){
            return view(detailedOutputViewName);
        }

        return view(detailedIndexViewName);
    }
    
    @RequestMapping(value = summaryIndexViewName, method = { RequestMethod.GET,RequestMethod.POST })
    public String summaryIndex(Model model,PagerModel pagerModel,BillingSearch search,boolean ajaxPost){
    	search.setType("notShipped");
    	search.setBillingState(BillingState.completed);
    	pagerModel.setTotalAmount(outStockCollocationService.queryCountBySummary(search));
    	List<BillingStat> billingStats=outStockCollocationService.queryListBySummary(search,pagerModel);
    	BillingStat billingStat=outStockCollocationService.querySummaryStat(search);
    	
    	model.addAttribute(WebManageContainer.PAGERKEY, pagerModel);
        model.addAttribute("billingStats", billingStats);
        model.addAttribute("billingStat", billingStat);
        model.addAttribute("billingSearch", search);

        if(ajaxPost){
            return view(summaryOutputViewName);
        }

        return view(summaryIndexViewName);
    }
    
    @RequestMapping(value = addDetailed, method = { RequestMethod.GET})
    public String addDetailed(Model model,String key,String type){
        Billing billing=new Billing();
     
        String timestamp = DateUtils.convertDate2String("yyyyMMddHHmmss", DateUtils.getCurrent());
        billing.setBillingNo("KD-"+timestamp);

        model.addAttribute("billing", billing);
        return view(addDetailed);
    }

    @RequestMapping(value = detailedViewName, method = { RequestMethod.GET})
    public String billingDetailed(Model model,String key,String type){
        Billing billing=new Billing();
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	
        }
        model.addAttribute("type", type);
        model.addAttribute("billing", billing);
        return view(detailedViewName);
    }

    @RequestMapping(value = saveViewName, method = { RequestMethod.POST})
    public String save(Model model,Billing billing,OutStockCollocationInfo outStockCollocationInfo,String mode){
    	
        if(StringUtils.isEmpty(billing.getBillingId())){
        	
            billing.setBillingId(CommonUtils.getKeyId());
            billing.setCreateDate(DateUtils.getCurrent());
            billing.setDeleteMark(YesOrNoInteger.no);
            billing.setCreateUserId(getLoginModel().getLoginId());
            billing.setCreateUserName(getLoginModel().getLoginName());
            billing.setModelStatus(ModelStatus.add);
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
            billing.setShopId(shop.getShopId());
            
            billing.setBillingState(BillingState.notShipped);
            billing.setUnpaidAmount(billing.getBillingMoney());
            billing.setPayState(PayState.unpaid);
            billing.setConfirm(BillingConfirm.unCheck);
        }else{
            billing.setModifyDate(DateUtils.getCurrent());
            billing.setModifyUserId(getLoginModel().getLoginId());
            billing.setModifyUserName(getLoginModel().getLoginName());
            billing.setModelStatus(ModelStatus.update);
        }
        Staff staff=staffService.queryModel(billing.getBusinessId());
        if(staff!=null) {
        	billing.setBusinessName(staff.getName());
        }
        
        ActionResult actionResult;
        if(billingService.applyBillingAndOutStock(billing,outStockCollocationInfo)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }
        model.addAttribute("billing", billing);
        model.addAttribute("mode", mode);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(addDetailed);
    }

    @RequestMapping(value =deleteViewName, method = { RequestMethod.POST },produces="text/plain;charset=utf-8")
    public @ResponseBody String delete(String key){
        if(billingService.deleteFakeByKey(key)){
            return new JsonActionResult(ManageContainer.SUCCESS).toJson();
        }
        return new JsonActionResult(ManageContainer.ERROR).toJson();
    }
    
    @RequestMapping(value = checkBillingState, method = { RequestMethod.GET},produces = "text/html;charset=UTF-8")
    public @ResponseBody String checkBillingState(Model model,String key){
    	String result = "banClose";
    	Billing billing=billingService.getBillingByKey(key);
    	if(billing!=null){
    		if(BillingState.notShipped.equals(billing.getBillingState())||BillingState.completed.equals(billing.getBillingState())||BillingState.returnOfCargo.equals(billing.getBillingState())) {
    			result = "allowClose";
    		}
    	}
        return result;
    }
    
    @RequestMapping(value = closeBillingByKey, method = { RequestMethod.POST},produces = "text/html;charset=UTF-8")
    public @ResponseBody String closeBillingByKey(Model model,String key){
		Billing billing =billingService.getBillingByKey(key);
    	
    	billingRecordService.saveBillingRecord(billing.getBillingId(),0.0,0.0,BillingRecordType.close,
				"",billing.getShopId(),getLoginModel().getLoginId(),getLoginModel().getLoginName());
    	
    	if(BillingState.returnOfCargo.equals(billing.getBillingState())) {
    		returnCargo(billing);
        	customerRecordService.saveCustomerRecord(billing.getCustomerId(),-billing.getBillingMoney(),0.0,CustomerRecordType.close,
    				billing.getBillingId(),billing.getShopId(),getLoginModel().getLoginId(),getLoginModel().getLoginName());
		}else {
			customerRecordService.saveCustomerRecord(billing.getCustomerId(),billing.getBillingMoney(),0.0,CustomerRecordType.close,
					billing.getBillingId(),billing.getShopId(),getLoginModel().getLoginId(),getLoginModel().getLoginName());
		}
    	
    	billing.setBillingState(BillingState.close);
    	billing.setModelStatus(ModelStatus.update);

    	if(!billingService.closeBilling(billing,getLoginModel().getLoginId(),getLoginModel().getLoginName())){
    		return new JsonActionResult(ManageContainer.ERROR).toJson();
    	}
		
		return new JsonActionResult(ManageContainer.SUCCESS).toJson();
    }
    
    @RequestMapping(value = checkDetailed, method = { RequestMethod.GET})
    public String checkDetailed(Model model,String key,String type){
        Billing billing=new Billing();
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	
        }

        model.addAttribute("type", type);
        model.addAttribute("typeJson", JsonUtils.writeValueAsString(type));
        model.addAttribute("billingJson", JsonUtils.writeValueAsString(billing));
        model.addAttribute("billing", billing);
        return view(checkDetailed);
    }
    
    @RequestMapping(value = checkSave, method = { RequestMethod.POST})
    public String checkSave(Model model,Billing billing,ReturnCargoInfo returnCargoInfo){
    	Billing billingYuan =billingService.getBillingByKey(billing.getBillingId());
    	billingYuan.setConfirm(BillingConfirm.checked);
    	billingYuan.setModelStatus(ModelStatus.update);
/*    	if(BillingState.returnOfCargo.equals(billingYuan.getBillingState())) {
    		returnCargo(billingYuan);
    	}*/
    	billingRecordService.saveBillingRecord(billing.getBillingId(),0.0,0.0,BillingRecordType.check,
				"",billing.getShopId(),getLoginModel().getLoginId(),getLoginModel().getLoginName());

        ActionResult actionResult;
        if(billingService.applyChange(billingYuan)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("billing", billing);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(checkDetailed);
    }
    
    private void returnCargo(Billing billing) {
    	Stock stock=new Stock();
    	List<StockCollocation> stockCollocations = new ArrayList<StockCollocation>();
    	for(OutStockShow outStockShow:billing.getOutStock().getOutStockShows()) {

			stock=stockService.queryModelByKey(outStockShow.getCargoId());
			if( stock!= null){
				stock.setModelStatus(ModelStatus.update);
				stock.setStockNum(stock.getStockNum() - outStockShow.getOutStockShowNum());
				stockService.applyChange(stock);
			}
			
	    	for (OutStockCollocation outStockCollocation : outStockShow.getOutStockCollocations()) {
	    		for(StockCollocation stockCollocation:stock.getStockCollocations()) {
					if(stockCollocation.getCollocationId().equals(outStockCollocation.getCollocationId())) {
						stockCollocation.setModelStatus(ModelStatus.update);
						stockCollocation.setCollocationNum(stockCollocation.getCollocationNum()-outStockCollocation.getCollocationNum()*outStockCollocation.getRatio());
						stockCollocations.add(stockCollocation);
					}
				}
	    	}
	    	stockCollocationService.applyChanges(stockCollocations);
    	}
    	
    }
    
    @RequestMapping(value = sendOutGoodsDetailed, method = { RequestMethod.GET})
    public String sendOutGoodsDetailed(Model model,String key){
        Billing billing=new Billing();
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        }

        model.addAttribute("billingJson", JsonUtils.writeValueAsString(billing));
        model.addAttribute("billing", billing);
        return view(sendOutGoodsDetailed);
    }
    
    @RequestMapping(value = sendOutGoodsSave, method = { RequestMethod.POST})
    public String sendOutGoodsSave(Model model,Billing billing,SendOutGoodsInfo sendOutGoodsInfo){
        if(StringUtils.isEmpty(billing.getBillingId())){
            billing.setBillingId(CommonUtils.getKeyId());
            billing.setCreateDate(DateUtils.getCurrent());
            billing.setDeleteMark(YesOrNoInteger.no);
            billing.setCreateUserId(getLoginModel().getLoginId());
            billing.setCreateUserName(getLoginModel().getLoginName());
            billing.setModelStatus(ModelStatus.add);
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
            billing.setShopId(shop.getShopId());
        }else{
            billing.setModifyDate(DateUtils.getCurrent());
            billing.setModifyUserId(getLoginModel().getLoginId());
            billing.setModifyUserName(getLoginModel().getLoginName());
            billing.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(outStockService.applySendOutGoods(billing,sendOutGoodsInfo)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("billing", billing);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(sendOutGoodsDetailed);
    }
    
    @RequestMapping(value = addPayDetailed, method = { RequestMethod.GET})
    public String addPayDetailed(Model model,String key,String paymentState){
        Billing billing=new Billing();
        Payment payment=new Payment();
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	payment.setBillingId(key);
        	payment.setBilling(billing);
        	payment.setAmount(billing.getUnpaidAmount());
        	payment.setCustomerId(billing.getCustomerId());
        }
        if(!StringUtils.isEmpty(paymentState)){
        	payment.setPaymentState(paymentState);
        }
        
        model.addAttribute("payment", payment);
        return view(addPayDetailed);
    }
    
    @RequestMapping(value = addPaySave, method = { RequestMethod.POST})
    public String addPaySave(Model model,Payment payment){
    	payment.setPayObject(PayObject.billing);
        if(StringUtils.isEmpty(payment.getPaymentId())){
            payment.setPaymentId(CommonUtils.getKeyId());
            payment.setCreateDate(DateUtils.getCurrent());
            payment.setDeleteMark(YesOrNoInteger.no);
            payment.setCreateUserId(getLoginModel().getLoginId());
            payment.setCreateUserName(getLoginModel().getLoginName());
            payment.setModelStatus(ModelStatus.add);
            Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
            payment.setShopId(shop.getShopId());
        }else{
            payment.setModifyDate(DateUtils.getCurrent());
            payment.setModifyUserId(getLoginModel().getLoginId());
            payment.setModifyUserName(getLoginModel().getLoginName());
            payment.setModelStatus(ModelStatus.update);
        }

        ActionResult actionResult;
        if(paymentService.applyPaymentAndBilling(payment)){
            actionResult=new ActionResult();
        }else{
            actionResult=new ErrorResult();
        }

        model.addAttribute("payment", payment);
        model.addAttribute(ManageContainer.RESULTKEY, actionResult);

        return view(addPayDetailed);
    }
    
    @RequestMapping(value = detailedPrint, method = { RequestMethod.GET})
    public String detailedPrint(Model model,String key){
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
    	
        Billing billing=new Billing();
        BillingPrint billingPrint=billingPrintService.getModelByType(PrintType.pioneer);
        if(billingPrint==null) {
        	billingPrint=new BillingPrint();
        }

        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        }
        model.addAttribute("shop", shop);
        model.addAttribute("billing", billing);
        model.addAttribute("billingPrint", billingPrint);
        return view(detailedPrint);
    }
    
    @RequestMapping(value = billingPrint, method = { RequestMethod.GET})
    public String billingPrint(Model model,String key,String describe){
        Billing billing=new Billing();
        Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
        BillingPrint print=billingPrintService.getModelByType(PrintType.pioneer);
        int count=0;
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	if(!StringUtils.isEmpty(billing.getOutStock().getOutStockShows())){
        		count=billing.getOutStock().getOutStockShows().size();
        	}
        }
        model.addAttribute("describe", describe);
        model.addAttribute("billing", billing);
        model.addAttribute("count", count);
        model.addAttribute("shop", shop);
        model.addAttribute("print", print);
        return view(billingPrint);
    }
    
    @RequestMapping(value = electricalPreview, method = { RequestMethod.GET})
    public String electricalPreview(Model model,String key){
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
        Billing billing=new Billing();
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	
        }
        model.addAttribute("billing", billing);
        model.addAttribute("shop", shop);
        return view(electricalPreview);
    }
    
    @RequestMapping(value = electricalPrint, method = { RequestMethod.GET})
    public String electricalPrint(Model model,String key,PrintDescribe printDescribe){
    	Shop shop=(Shop)webSessionFactory.getCurrentLogin().getArgument("shop");
        Billing billing=new Billing();
        int count=0;
        if(!StringUtils.isEmpty(key)){
        	billing =billingService.getBillingByKey(key);
        	if(!StringUtils.isEmpty(billing.getOutStock().getOutStockShows())){
        		count=billing.getOutStock().getOutStockShows().size();
        	}
        	
        }
        model.addAttribute("printDescribe", printDescribe);
        model.addAttribute("billing", billing);
        model.addAttribute("count", count);
        model.addAttribute("shop", shop);
        return view(electricalPrint);
    }
    
    //导出详细信息
	@RequestMapping(value = exportDetailed, method = { RequestMethod.GET,RequestMethod.POST }, produces = "text/plain;charset=utf-8")
	public void exportDetailed(String key, HttpServletResponse res) {
		String fileName = "";
		Billing billing =billingService.getBillingByKey(key);
		Date date = DateUtils.getCurrent();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = dateFormat.format(date);
		
		String moduleNo =billing.getBillingNo();
		// ---------------------------------------------------
		fileName = moduleNo +"(" + dateString + ").xls";

		// 声明一个工作薄
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet sheet = workbook.createSheet("订单");

		// 大标题的样式
		HSSFCellStyle styleTitle = workbook.createCellStyle(); // 宋体 24
		styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中格式
		styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		// 生成一个字体
		HSSFFont fontTitle = workbook.createFont();
		fontTitle.setFontName("宋体");
		fontTitle.setFontHeightInPoints((short) 20);// 设置字体大小
		fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		styleTitle.setFont(fontTitle);

		int rowindex = 0;

		// 大标题
		HSSFRow rowTitle = sheet.createRow(rowindex);
		if(BillingState.returnOfCargo.equals(billing.getBillingState())) {
			rowTitle.createCell(0).setCellValue("退  货  订  单  信  息");
		}else if(BillingState.close.equals(billing.getBillingState())){
			rowTitle.createCell(0).setCellValue("关  闭  订  单  信  息");
		}else {
			rowTitle.createCell(0).setCellValue("订  单  信  息");
		}
		

		rowTitle.getCell(0).setCellStyle(styleTitle);
		rowTitle.setHeight((short) 700);// 行高46.5*20

		// 标题的格式
		HSSFCellStyle styleSubTitle = workbook.createCellStyle();
		styleSubTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中格式
		styleSubTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		styleSubTitle.setWrapText(true);// 设置自动换行
		styleSubTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置边框
		styleSubTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		styleSubTitle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		styleSubTitle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		HSSFFont fontSubTitle = workbook.createFont();// 宋体 9
		fontSubTitle.setFontName("宋体");
		fontSubTitle.setFontHeightInPoints((short) 10);// 设置字体大小
		fontSubTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		styleSubTitle.setFont(fontSubTitle);

		HSSFRow rowSerialNoTitle = sheet.createRow(++rowindex);
		rowSerialNoTitle.createCell(0).setCellValue("订单号");
		rowSerialNoTitle.createCell(1).setCellValue(billing.getBillingNo());
		rowSerialNoTitle.createCell(3).setCellValue("下单日期");
		rowSerialNoTitle.createCell(4).setCellValue(dateFormat.format(billing.getCreateDate()));
		rowSerialNoTitle.createCell(6).setCellValue("开单人");
		rowSerialNoTitle.createCell(7).setCellValue(billing.getCreateUserName());
		

		rowSerialNoTitle.setHeight((short) 500);// 行高40*20

		for (int i = 0; i < 9; i++) {// 创建空格并赋予样式
			HSSFCell cell = rowSerialNoTitle.getCell(i);
			if (cell == null) {
				rowSerialNoTitle.createCell(i).setCellValue("");
			}
			rowSerialNoTitle.getCell(i).setCellStyle(styleSubTitle);
		}


		rowSerialNoTitle = sheet.createRow(++rowindex);
		
		rowSerialNoTitle.createCell(0).setCellValue("客户");
		rowSerialNoTitle.createCell(1).setCellValue(billing.getCustomer().getCustomerName());
		rowSerialNoTitle.createCell(3).setCellValue("项目名称");

		rowSerialNoTitle.createCell(6).setCellValue("合同编号");

		
		rowSerialNoTitle.setHeight((short) 500);// 行高25.5*20
		
		for (int i = 0; i < 9; i++) {// 创建空格并赋予样式
			HSSFCell cell = rowSerialNoTitle.getCell(i);
			if (cell == null) {
				rowSerialNoTitle.createCell(i).setCellValue("");
			}
			rowSerialNoTitle.getCell(i).setCellStyle(styleSubTitle);
		}

		rowSerialNoTitle = sheet.createRow(++rowindex);
		rowSerialNoTitle.createCell(0).setCellValue("收货地址");
		rowSerialNoTitle.createCell(1).setCellValue(billing.getAddress());
		rowSerialNoTitle.createCell(6).setCellValue("客户电话");
		rowSerialNoTitle.createCell(7).setCellValue(billing.getCustomer().getCustomerTel());
		rowSerialNoTitle.setHeight((short) 500);// 行高25.5*20

		for (int i = 0; i < 9; i++) {// 创建空格并赋予样式
			HSSFCell cell = rowSerialNoTitle.getCell(i);
			if (cell == null) {
				rowSerialNoTitle.createCell(i).setCellValue("");
			}
			rowSerialNoTitle.getCell(i).setCellStyle(styleSubTitle);
		}

		// 空行
		rowSerialNoTitle = sheet.createRow(++rowindex);

		sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, 5));
		sheet.addMergedRegion(new CellRangeAddress(1, 1, 7, 8));
		sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 2));
		sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 5));
		sheet.addMergedRegion(new CellRangeAddress(2, 2, 7, 8));
		sheet.addMergedRegion(new CellRangeAddress(3, 3, 1, 5));
		sheet.addMergedRegion(new CellRangeAddress(3, 3, 7, 8));

		// 标题2的格式
		HSSFCellStyle styleSubTitle3 = workbook.createCellStyle();
		styleSubTitle3.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中格式
		styleSubTitle3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		styleSubTitle3.setWrapText(true);// 设置自动换行
		styleSubTitle3.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置边框
		styleSubTitle3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		styleSubTitle3.setBorderRight(HSSFCellStyle.BORDER_THIN);
		styleSubTitle3.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);
		HSSFFont fontSubTitle3 = workbook.createFont();// 宋体 10.5 没有10.5设为11
		fontSubTitle3.setFontName("宋体");
		fontSubTitle3.setFontHeightInPoints((short) 10);// 设置字体大小
		fontSubTitle3.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		styleSubTitle3.setFont(fontSubTitle3);

		rowSerialNoTitle = sheet.createRow(++rowindex);
		rowSerialNoTitle.createCell(0).setCellValue("序号");
		rowSerialNoTitle.createCell(1).setCellValue("商品编号");
		rowSerialNoTitle.createCell(3).setCellValue("商品名称");
		rowSerialNoTitle.createCell(4).setCellValue("规格1");
		rowSerialNoTitle.createCell(5).setCellValue("规格2");
		rowSerialNoTitle.createCell(6).setCellValue("数量");
		rowSerialNoTitle.createCell(7).setCellValue("单价");
		rowSerialNoTitle.createCell(8).setCellValue("小计");
		rowSerialNoTitle.setHeight((short) 500);// 行高25.5*20

		for (int i = 0; i < 9; i++) {// 创建空格并赋予样式
			HSSFCell cell = rowSerialNoTitle.getCell(i);
			if (cell == null) {
				rowSerialNoTitle.createCell(i).setCellValue("");
			}
			rowSerialNoTitle.getCell(i).setCellStyle(styleSubTitle3);
		}

		// 数据2的格式
		HSSFCellStyle styleContent3 = workbook.createCellStyle();
		styleContent3.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中格式
		styleContent3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
		styleContent3.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 设置边框
		styleContent3.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		styleContent3.setBorderRight(HSSFCellStyle.BORDER_THIN);
		styleContent3.setWrapText(true);// 设置自动换行
		HSSFFont fontContent3 = workbook.createFont();// 宋体 12 不加粗
		fontContent3.setFontName("宋体");
		fontContent3.setFontHeightInPoints((short) 8);// 设置字体大小
		styleContent3.setFont(fontContent3);
		int num=0;
		Double nullAll=0.0;
		double realPriceAll=0;
		HSSFRow row1;
		for(OutStockShow outStockShow:billing.getOutStock().getOutStockShows()) {
			for(OutStockCollocation outStockCollocation:outStockShow.getOutStockCollocations()) {
				row1 = sheet.createRow(++rowindex);
				row1.setHeight((short) 500);// 行高25.5*20
				num++;
				nullAll=nullAll+outStockCollocation.getCollocationNum();
				realPriceAll=realPriceAll+outStockCollocation.getCollocationNum()*outStockCollocation.getRealPrice();
				row1.createCell(0).setCellValue(num);
				row1.createCell(1).setCellValue(outStockShow.getCargo().getCargoNo());
				row1.createCell(3).setCellValue(outStockShow.getCargo().getCargoName());
				row1.createCell(4).setCellValue(outStockCollocation.getCollocation().getPropertyNameOne());
				row1.createCell(5).setCellValue(outStockCollocation.getCollocation().getPropertyNameTwo());
				row1.createCell(6).setCellValue(outStockCollocation.getCollocationNum());
				row1.createCell(7).setCellValue(outStockCollocation.getRealPrice());
				row1.createCell(8).setCellValue(outStockCollocation.getCollocationNum()*outStockCollocation.getRealPrice());
				

				for (int j = 0; j < 9; j++) {// 创建空格并赋予样式
					HSSFCell cell = row1.getCell(j);
					if (cell == null) {
						row1.createCell(j).setCellValue("");
					}
					row1.getCell(j).setCellStyle(styleContent3);
				}
				
				sheet.addMergedRegion(new CellRangeAddress(rowindex, rowindex, 1, 2));
			}
			
		}
		sheet.addMergedRegion(new CellRangeAddress(5, 5, 1, 2));
		
		// 合计
		HSSFRow rowCommnets = sheet.createRow(++rowindex);
		rowCommnets.createCell(0).setCellValue("合计");
		rowCommnets.createCell(6).setCellValue(nullAll);
		rowCommnets.createCell(7).setCellValue("");
		rowCommnets.createCell(8).setCellValue(realPriceAll);
		rowCommnets.setHeight((short) 500);// 行高39.75*20

		for (int i = 0; i < 9; i++) {// 创建空格并赋予样式
			HSSFCell cell = rowCommnets.getCell(i);
			if (cell == null) {
				rowCommnets.createCell(i).setCellValue("");
			}
			rowCommnets.getCell(i).setCellStyle(styleContent3);
		}



		sheet.addMergedRegion(new CellRangeAddress(rowindex, rowindex, 0, 5));


		// int curColWidth=0;

		int[] defaultColWidth = { 2000, 3100, 3500, 2500, 2000, 2000, 1300, 1300, 1300, 3500, 1250, 1250, 1250, 1250,
				1250, 1250, 1250, 1250, 1250 };
		/* 实际宽度 < 默认宽度的时候、设置为默认宽度 */
		for (int i = 0; i < 8; i++) {
			sheet.setColumnWidth(i, defaultColWidth[i]);
		}

		OutputStream out = null;
		try {
			res.reset();
			res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
			res.setContentType("application/vnd.ms-excel; charset=utf-8");
			// 创建输出位置
			out = res.getOutputStream();
			// 输出
			workbook.write(out);
			// 清空缓冲区
			out.flush();
			// 关闭流，关闭前会清空缓冲区
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping(value = returnCheck, method = { RequestMethod.GET})
	public String returnCheck(Model model,String key){
	    Billing billing=new Billing();
	    if(!StringUtils.isEmpty(key)){
	    	billing =billingService.getBillingByKey(key);
	    	
	    }
	    model.addAttribute("billing", billing);
	    return view(returnCheck);
	}
	 
	@RequestMapping(value = returnCheckSave, method = { RequestMethod.POST})
    public String returnCheckSave(Model model,Billing billing,OutStockCollocationInfo outStockCollocationInfo){
    	
       
        billing.setModifyDate(DateUtils.getCurrent());
        billing.setModifyUserId(getLoginModel().getLoginId());
        billing.setModifyUserName(getLoginModel().getLoginName());
        billing.setBillingState(BillingState.notShipped);
        billing.setConfirm(BillingConfirm.unCheck);
        billing.setModelStatus(ModelStatus.update);
	    
	    Staff staff=staffService.queryModel(billing.getBusinessId());
	    if(staff!=null) {
	    	billing.setBusinessName(staff.getName());
	    }
	    
	    ActionResult actionResult;
	    if(billingService.applyBillingReturnCheck(billing,outStockCollocationInfo)){
	        actionResult=new ActionResult();
	    }else{
	        actionResult=new ErrorResult();
	    }
	    model.addAttribute("billing", billing);
	    model.addAttribute(ManageContainer.RESULTKEY, actionResult);
	
	    return view(addDetailed);
	}
}
